package com.indusfo.spc.service.impl;

import com.indusfo.spc.exception.GlobalException;
import com.indusfo.spc.exception.ModifyFailedException;
import com.indusfo.spc.exception.ParamsErrorException;
import com.indusfo.spc.mapper.InspectMapper;
import com.indusfo.spc.mapper.InspectWorkDetailMapper;
import com.indusfo.spc.mapper.InspectWorkMapper;
import com.indusfo.spc.pojo.Inspect;
import com.indusfo.spc.pojo.InspectWork;
import com.indusfo.spc.pojo.InspectWorkDetail;
import com.indusfo.spc.service.InspectWorkService;
import com.indusfo.spc.vo.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class InspectWorkServiceImpl implements InspectWorkService {

    private  static  final Logger logger = LoggerFactory.getLogger(InspectWorkServiceImpl.class);

    @Resource
    private InspectWorkMapper inspectWorkMapper;

    @Resource
    private InspectMapper inspectMapper;

    @Resource
    private InspectWorkDetailMapper inspectWorkDetailMapper;

    /**
     * 查询点检作业
     * @param inspectWork
     * @return
     */
    @Override
    public JSONObject selectInspectWork(InspectWork inspectWork,String startDate,String endDate) {
        List<InspectWork> inspectWorkList = null;
        int count = 0;
        try {
            Integer pagesize = inspectWork.getPagesize();
            Integer pageindex = inspectWork.getPageindex();
            if(pagesize != null && pageindex != null) {
                inspectWork.setIncept(pagesize*(pageindex - 1));
            }
            if(!org.apache.commons.lang3.StringUtils.isEmpty(startDate)){
                try {
                    Date parse = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(startDate);
                } catch (ParseException e) {
                    return JSONObject.build(JSONObject.ERROR,"开始日期格式错误");
                }
            }
            if(!org.apache.commons.lang3.StringUtils.isEmpty(endDate)){
                try {
                    Date parse = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(endDate);
                } catch (ParseException e) {
                    return JSONObject.build(JSONObject.ERROR,"结束日期格式错误");
                }
            }
            inspectWorkList = inspectWorkMapper.selectInspectWork(inspectWork,startDate,endDate);
            //查询分页总记录数
            count = inspectWorkMapper.countInspectWork(inspectWork,startDate,endDate); //返回查询到的总记录数
            if (inspectWorkList.isEmpty()) {
                return JSONObject.oK("没有查询到相关数据", inspectWorkList, count);
            }
            return JSONObject.oK("查询成功", inspectWorkList, count);
        } catch (
                GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    /**
     * 新增
     * @param inspectWork
     * @return
     */
    @Transactional
    @Override
    public JSONObject insertInspectWork(InspectWork inspectWork,Integer[] qualifiedIds) {
        if(inspectWork.getInspectWorkId()!= null) {
            throw new ParamsErrorException("新增时，不能填写id");
        }
        checkParam(inspectWork);
        // 调用存储过程
        int row = inspectWorkMapper.insertSelective(inspectWork);
        if(row == 0) {
            throw new ModifyFailedException("数据新增失败");
        }
//        Integer inspectWorkId = inspectWork.getInspectWorkId();
//        Integer[] inspectIds = inspectWork.getInspectIds();
//        if(inspectIds!=null && inspectIds.length!=0){
//            int updateCount = inspectWorkDetailMapper.insertInspectWorkDetail(inspectWorkId, inspectIds);
//            if(updateCount>0){
//                return JSONObject.build(JSONObject.SUCCESS,"新增成功");
//            }
//            return JSONObject.build(JSONObject.ERROR,"新增设备点检明细失败");
//        }
        Integer[] inspectIds = inspectWork.getInspectIds();
        boolean judgeFlag1=false;
        boolean judgeFlag2=false;
        boolean judgeFlag3=false;
        if(inspectIds==null && qualifiedIds!=null){
            judgeFlag1=true;
        }
        if(inspectIds!=null && qualifiedIds==null){
            judgeFlag2=true;
        }
        if(inspectIds!=null && qualifiedIds!=null && inspectIds.length!=qualifiedIds.length){
            judgeFlag3=true;
        }
        //判断两个数组是否长度一样
        if( judgeFlag1 || judgeFlag2 || judgeFlag3 ){
            return JSONObject.build(JSONObject.ERROR,"保养明细与状态信息不匹配");
        }else if(inspectIds!=null && inspectIds.length>0){
            List<InspectWorkDetail> inspectWorkDetailList=new ArrayList<>();
            for (int i = 0; i < inspectIds.length; i++) {
                InspectWorkDetail inspectWorkDetail=new InspectWorkDetail(inspectWork.getInspectWorkId(),inspectIds[i],qualifiedIds[i]);
                inspectWorkDetailList.add(inspectWorkDetail);
            }
            //直接对传递过来的数组进行新增到明细中
            int insertInspectWorkDetailList = inspectWorkDetailMapper.insertInspectWorkDetailList(inspectWorkDetailList);
        }
        return JSONObject.oK("新增成功");
    }

    /**
     * 修改
     * @param inspectWork
     * @return
     */
    @Transactional
    @Override
    public JSONObject updateInspectWork(InspectWork inspectWork,Integer[] qualifiedIds) {
        if(inspectWork.getInspectWorkId()== null || "".equals(inspectWork.getInspectWorkId())) {
            throw new ParamsErrorException("请选择要编辑的点检作业");
        }
        checkParam(inspectWork);
//        Integer[] inspectIds = inspectWork.getInspectIds();
//        //查询当前设备保养计划的明细保养项目
//        List<Integer> inspectIdList = inspectWorkDetailMapper.queryByInspectWork(inspectWork.getInspectWorkId());
//        List<Integer> insertList=new ArrayList<>();
//        List<Integer> deleteList=new ArrayList<>();
//        if(inspectIds!=null && inspectIds.length!=0 && !inspectIdList.isEmpty()){
//            List<Integer> tempInspectIds=new ArrayList<>();
//            for (Integer id : inspectIds) {
//                tempInspectIds.add(id);
//            }
//            for (Integer inspectId : inspectIds) {
//                //不包含说明是要进行新增的
//                if(!inspectIdList.contains(inspectId)){
//                    insertList.add(inspectId);
//                }
//            }
//            //传递过来的数组不包含当前数据库查询出来的则为要进行删除的
//            for (Integer inspectId : inspectIdList) {
//                if(!tempInspectIds.contains(inspectId)){
//                    deleteList.add(inspectId);
//                }
//            }
//            if(!insertList.isEmpty()){
//                inspectWorkDetailMapper.insertInspectWorkDetail(inspectWork.getInspectWorkId(),insertList.toArray(new Integer[insertList.size()]));
//            }
//            if(!deleteList.isEmpty()){
//                inspectWorkDetailMapper.defineInspectWorkDetail(inspectWork.getInspectWorkId(),deleteList.toArray(new Integer[deleteList.size()]),2);
//            }
//        }else if((inspectIds==null || inspectIds.length==0) && !inspectIdList.isEmpty()){
//            //如果传递的数据为空,而数据库数据存在则删除数据库中的数据
//            inspectWorkDetailMapper.defineInspectWorkDetail(inspectWork.getInspectWorkId(),inspectIdList.toArray(new Integer[inspectIdList.size()]),2);
//        }else if((inspectIds!=null && inspectIds.length!=0) && inspectIdList.isEmpty()){
//            //如果传递的数据不为空,而数据库不存在数据则进行新增
//            inspectWorkDetailMapper.insertInspectWorkDetail(inspectWork.getInspectWorkId(),inspectIds);
//        }
        Integer[] inspectIds = inspectWork.getInspectIds();
        Map<Integer,InspectWorkDetail> inspectWorkDetailMap=new HashMap<>();
        boolean judgeFlag1=false;
        boolean judgeFlag2=false;
        boolean judgeFlag3=false;
        if(inspectIds==null && qualifiedIds!=null){
            judgeFlag1=true;
        }
        if(inspectIds!=null && qualifiedIds==null){
            judgeFlag2=true;
        }
        if(inspectIds!=null && qualifiedIds!=null && inspectIds.length!=qualifiedIds.length){
            judgeFlag3=true;
        }
        //判断两个数组是否长度一样
        if( judgeFlag1 || judgeFlag2 || judgeFlag3 ){
            return JSONObject.build(JSONObject.ERROR,"保养明细与状态信息不匹配");
        }else {
            for (int i = 0; i < inspectIds.length; i++) {
                InspectWorkDetail inspectWorkDetail=new InspectWorkDetail(inspectWork.getInspectWorkId(),inspectIds[i],qualifiedIds[i]);
                inspectWorkDetailMap.put(inspectIds[i],inspectWorkDetail);
            }
            //获取当前设备保养作业下的所有明细的保养项目id
            List<Integer> queryInspectIdList = inspectWorkDetailMapper.queryByInspectWork(inspectWork.getInspectWorkId());
            List<InspectWorkDetail> insertList=new ArrayList<>();
            List<InspectWorkDetail> deleteList=new ArrayList<>();
            List<InspectWorkDetail> updateList=new ArrayList<>();
            //所传递的数组当中不存在数据库查询的集合说明删除了,数据库查询的集合中不存在传递的数组说明是新增
            if(!inspectWorkDetailMap.isEmpty() && !queryInspectIdList.isEmpty()){
                for (int i = 0; i < inspectIds.length; i++) {
                    InspectWorkDetail inspectWorkDetail=new InspectWorkDetail(inspectWork.getInspectWorkId(),inspectIds[i],qualifiedIds[i]);
                    inspectWorkDetailMap.put(inspectIds[i],inspectWorkDetail);
                }
                for (Integer inspectId : inspectIds) {
                    //不包含说明是要进行新增的
                    if(!queryInspectIdList.contains(inspectId)){
                        insertList.add(inspectWorkDetailMap.get(inspectId));
                    }
                }
                for (Integer inspectId : queryInspectIdList) {
                    if(!inspectWorkDetailMap.containsKey(inspectId)){
                        InspectWorkDetail inspectWorkDetail = new InspectWorkDetail();
                        inspectWorkDetail.setInspectWorkId(inspectWork.getInspectWorkId());
                        inspectWorkDetail.setInspectId(inspectId);
                        deleteList.add(inspectWorkDetail);
                    }else{
                        updateList.add(inspectWorkDetailMap.get(inspectId));
                    }
                }
                if(!insertList.isEmpty()){
                    inspectWorkDetailMapper.insertInspectWorkDetailList(insertList);
                }
                if(!deleteList.isEmpty()){
                    inspectWorkDetailMapper.defineInspectWorkDetailList(deleteList,2);
                }
                if(!updateList.isEmpty()){
                    inspectWorkDetailMapper.updateInspectWorkDetailList(updateList);
                }
            }else if(inspectWorkDetailMap.isEmpty() && !queryInspectIdList.isEmpty()){
                //如果传递的明细数据为空,而数据库数据存在明细数据则说明删除删除数据库中的数据
                inspectWorkDetailMapper.defineInspectWorkDetail(inspectWork.getInspectWorkId(),queryInspectIdList.toArray(new Integer[queryInspectIdList.size()]),2);
            }else if(!inspectWorkDetailMap.isEmpty() && queryInspectIdList.isEmpty()){
                //如果传递的数据不为空,而数据库不存在数据则只进行新增
                for (Integer inspectId : inspectWorkDetailMap.keySet()) {
                    insertList.add(inspectWorkDetailMap.get(inspectId));
                }
                inspectWorkDetailMapper.insertInspectWorkDetailList(insertList);
            }
            // 调用存储过程
            int row = inspectWorkMapper.updateByPrimaryKeySelective(inspectWork);
            if(row>0){
                return JSONObject.build(JSONObject.SUCCESS,"编辑成功");
            }
            return JSONObject.build(JSONObject.ERROR,"编辑失败");
        }

    }

    /**
     * 停用/启用/删除
     * @param inspectWorkIds
     * @param dataState
     * @return
     */
    @Override
    public JSONObject definedInspectWork(Long[] inspectWorkIds,Integer[] auditStates , Integer dataState) {
        try {
            if(dataState == null) {
                throw new ParamsErrorException("数据状态不能为空");
            }else if(dataState != 1 && dataState != 2 && dataState != 3) {
                throw new ParamsErrorException("数据状态错误");
            }
            if (inspectWorkIds == null) {
                throw new ParamsErrorException("点检作业id不能为空");
            }
            for(Integer i: auditStates){
                if(i == 2){
                    throw new ParamsErrorException("已审核的无法删除");
                }
            }
            // 执行存储过程
            int row = inspectWorkMapper.definedInspectWork(inspectWorkIds, dataState);
            String msg = "";
            if (row == 0) {
                // 判断传入的数据状态参数lDataState,返回相应信息
                switch (dataState) {
                    case 1:
                        throw new ModifyFailedException("启用失败");
                    case 2:
                        throw new ModifyFailedException("删除失败");
                    case 3:
                        throw new ModifyFailedException("停用失败");
                    default:
                }
            } else {
                switch (dataState) {
                    case 1:
                        msg = "启用成功";break;
                    case 2:
                        msg = "删除成功";
                        break;
                    case 3:
                        msg = "停用成功";break;
                    default:
                }
            }
            return JSONObject.oK(msg);
        } catch (GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    /**
     * 审核/反审核
     * @param inspectWorkIds
     * @param auditStates
     * @param auditState
     * @return
     */
    @Override
    public JSONObject auditInspectWork(Long[] inspectWorkIds, Integer[] auditStates, Integer auditState) {
        if(auditState == null) {
            throw new ParamsErrorException("审核状态不能为空");
        }else if(auditState != 1 && auditState != 2 ) {
            throw new ParamsErrorException("审核状态错误");
        }
        if (inspectWorkIds == null || inspectWorkIds.length == 0) {
            throw new ParamsErrorException("ID不能为空");
        }
        if (auditStates == null || auditStates.length == 0) {
            throw new ParamsErrorException("审核状态数组不能为空");
        }
        for(Integer i : auditStates){
            if(auditState == 1){
                if(i == auditState){
                    throw new ParamsErrorException("未审核的不能反审核");
                }
            }else {
                if(i == auditState){
                    throw new ParamsErrorException("已审核的不能审核");
                }
            }
        }
        // 执行存储过程
        int row = inspectWorkMapper.auditInspectWork(inspectWorkIds, auditState);
        String msg = "";
        if (row == 0) {
            // 判断传入的审核状态参数auditState,返回相应信息
            switch (auditState) {
                case 1:
                    throw new ModifyFailedException("反审核失败");
                case 2:
                    throw new ModifyFailedException("审核失败");
                default:
            }
        } else {
            switch (auditState) {
                case 1:
                    msg = "反审核成功";break;
                case 2:
                    msg = "审核成功";break;
                default:
            }
        }
        return JSONObject.oK(msg);
    }

    /**
     * 查询设备相关点检
     * @param inspectWork
     * @return
     */
    @Override
    public JSONObject queryInspectByDevice(InspectWork inspectWork) {
        try {
            List<Inspect> inspectList = new ArrayList<>();
            if(inspectWork.getDeviceId()!=null && !"".equals(inspectWork.getDeviceId())){
                 inspectList = inspectMapper.queryByDevice(inspectWork.getDeviceId());
                if(inspectList.isEmpty()){
                    return JSONObject.oK("查询成功",inspectList,0);
                }
            }
            return JSONObject.oK("查询成功",inspectList,inspectList.size());
        } catch (GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    /**
     * 查询明细
     * @param inspectWorkDetail
     * @return
     */
    @Override
    public JSONObject queryInspectWorkDetail(InspectWorkDetail inspectWorkDetail) {
        try{
            Integer pagesize = inspectWorkDetail.getPagesize();
            Integer pageindex = inspectWorkDetail.getPageindex();
            if(pagesize != null && pageindex != null) {
                inspectWorkDetail.setIncept(pagesize*(pageindex - 1));
            }
            List<InspectWorkDetail> inspectWorkDetailList = inspectWorkDetailMapper.queryInspectWorkDetail(inspectWorkDetail);
            if(!inspectWorkDetailList.isEmpty()){
                int count = inspectWorkDetailMapper.countInspectWorkDetail(inspectWorkDetail);
                return new JSONObject("查询成功",inspectWorkDetailList,count);
            }
            return new JSONObject("查询成功",inspectWorkDetailList,null);
        } catch (GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    /**
     * 新增设备点检作业明细时查询点检项目
     * @param inspectWork
     * @return
     */
    @Override
    public JSONObject filterInspectList(InspectWork inspectWork) {
        List<Inspect> inspectList=new ArrayList<>();
        Integer[] inspectIds = inspectWork.getInspectIds();
        Integer pagesize = inspectWork.getPagesize();
        Integer pageindex = inspectWork.getPageindex();
        Integer incept=null;
        if(pagesize != null && pageindex != null) {
            inspectWork.setIncept(pagesize*(pageindex - 1));
            incept=pagesize*(pageindex - 1);
        }
        if(inspectIds==null || "".equals(inspectIds) || inspectIds.length==0) {
            inspectIds = null;
        }
        inspectList = inspectMapper.filterInspectListByInspectIds(pagesize,incept,inspectIds);

        if(!inspectList.isEmpty()){
            int  count = inspectMapper.countFilterInspectListByInspectIds(inspectIds);
            return JSONObject.oK(inspectList,count);
        }
        return JSONObject.oK(inspectList,null);
    }

    /**
     * 参数校验
     */
    private void checkParam(InspectWork inspectWork) {
        if (inspectWork.getDeviceId() == null) {
            throw new ParamsErrorException("请选择设备");
        }
        if (StringUtils.isEmpty(inspectWork.getInspectWorkNo())) {
            throw new ParamsErrorException("请填写点检作业单号");
        }
        if (inspectWork.getInspectWorkNo().getBytes().length > 50) {
            throw new ParamsErrorException("点检作业单号超过规定,长度50");
        }
        // 单号不能重复
        Integer codeCounts = inspectWorkMapper.queryInspectWorkCode(inspectWork);
        if (codeCounts !=0) {
            throw new ParamsErrorException("该点检作业单号已存在");
        }
    }
    
}
